package com.zretc.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.aliyuncs.exceptions.ClientException;
import com.zretc.entity.Seller;
import com.zretc.service.SellerService;
import com.zretc.service.impl.SellerServiceImpl;
import com.zretc.util.SmsDemo;

/**
 * Servlet implementation class SellerServlet
 */
@WebServlet("/back/SellerServlet")
@MultipartConfig
public class SellerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	SellerService sellerService = new SellerServiceImpl();
	private boolean key;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SellerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        // 设置请求参数的编码格式
				request.setCharacterEncoding("UTF-8");

				// 接收请求中的参数op,请求操作标识
				String op = request.getParameter("op");
				if (op == null) {
					// 前往登录页面
				response.sendRedirect("sellerSignIn.jsp");
				} else if ("login".equals(op)) {
					doLogin(request, response);
				} else if ("logout".equals(op)) {
					doLogout(request, response);
				} else if ("register".equals(op)) {
					doRegister(request, response);
				} else if("existsOfAccountName".equals(op)) {
					// 判断用户名是否存在
					doExistsOfSellerAccount(request,response);
			    }else if("existsOfSellerPhone".equals(op)) {
					// 判断手机号是否存在
			    	doExistsOfSellerPhone(request,response);
			    }else if("existsOfSellerShopName".equals(op)) {
					// 判断手机号是否存在
			    	doExistsOfSellerShopName(request,response);
			    }else if("sellerPhoneCodeCheck".equals(op)) {
					// 验证验证码
			    	sellerPhoneCodeCheck(request,response);
			    }else if("phoneCode".equals(op)) {
				   // 发送手机验证码
		    
			    	try {
						doPhoneCode(request,response);
					} catch (ClientException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			
		    }
			}
	
	/**
	 * 发送验证码
	 * @throws ClientException 
	 * @throws IOException 响应错误
	 */
	
	private void doPhoneCode(HttpServletRequest request, HttpServletResponse response) throws ClientException, IOException {
		String sellerPhone = request.getParameter("sellerPhone");
		SmsDemo.sendSms(sellerPhone,request);
		response.getWriter().write("true");   
	}
	
	
	/**
	 * 验证验证码
	 * @throws IOException 响应错误
	 */
	

	private void sellerPhoneCodeCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String code = request.getParameter("sellerPhoneCode");  	
		response.setCharacterEncoding("UTF-8"); 
		System.out.println(request.getSession().getAttribute("sellerPhoneCode"));
		if(request.getSession().getAttribute("sellerPhoneCode").equals(code)){
			key = true;
			response.getWriter().write("true");   
		}else {
			response.getWriter().write("false");   
		}
		response.flushBuffer();   
		
	}

	private void doExistsOfSellerShopName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String sellerShopName = request.getParameter("sellerShopName");
		boolean existsOfSellerShopName = sellerService.existsOfSellerShopName(sellerShopName);
		// 响应数据
		response.getWriter().write(existsOfSellerShopName+"");
		
	}

	private void doExistsOfSellerPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String sellerPhone = request.getParameter("sellerPhone");
		boolean existsOfSellerPhone = sellerService.existsOfSellerPhone(sellerPhone);
		// 响应数据
		response.getWriter().write(existsOfSellerPhone+"");
		
	}

	private void doExistsOfSellerAccount(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String sellerAccount = request.getParameter("sellerAccount");
		boolean existsOfSellerAccount = sellerService.existsOfSellerName(sellerAccount);
		// 响应数据
		response.getWriter().write(existsOfSellerAccount+"");
	}

	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 业务逻辑层
		if(key=true) {
		Integer sellerId = null ;
		String sellerAccount = request.getParameter("sellerAccount");
		String sellerPassword = request.getParameter("sellerPassword");
		String sellerAddress = request.getParameter("sellerAddress");
		String sellerPhone = request.getParameter("sellerPhone");
		String sellerShopName = request.getParameter("sellerShopName");
		Integer sellerStatus = 0;
		
		// 接收文件组件
		Part part = request.getPart("sellerLogo");
		// 判断用户是否有上传文件
		if(part.getSize() == 0) { // 没有上传
			// 业务逻辑层
			Seller seller = new Seller(sellerId,sellerAccount,sellerPassword,sellerAddress,sellerPhone,sellerShopName,null,sellerStatus);
			sellerService.insertShop(seller);
		}else { // 有上传
			
			// 允许的文件图片类型
			String allowImgType ="image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
			
			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			
			// 判断上传的文件MIME类型是否在指定的允许类型集合
			if(allowImgTypeList.contains(contentType)==false) {
				System.out.println("文件类型不匹配!");
				// 重定向注册页面,提示文件不合法
				response.sendRedirect("register.jsp?fileuploaderror=fileuploaderror");
				return;
			}else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);	
				// 随机数
				int random = (int) (Math.random()*1000+1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);
				
				// 将文件存储在指定服务器中(本地电脑E盘)
				File file = new File("D:\\upload\\images");
				
				// 将文件写入指定位置
				String filePath = file.getPath() + File.separator + fileName + fileSuffix; // E:\fileupload\images\1.jpg
				part.write(filePath);
				
				String sellerLogo = fileName + fileSuffix;
				
				// 调用业务层
				Seller seller = new Seller(sellerId,sellerAccount,sellerPassword,sellerAddress,sellerPhone,sellerShopName,sellerLogo,sellerStatus);
				sellerService.insertShop(seller);
			}
		}
		
		// 重定向到前台首页
		response.sendRedirect("sellerSignIn.jsp");
		}else {
			response.getWriter().write("验证码错误");
		}
		
	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("seller");
		response.sendRedirect("sellerSignIn.jsp");
		
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		            // 调度器
				String sellerAccount = request.getParameter("sellerAccount");
				String sellerPassword = request.getParameter("sellerPassword");
				Seller seller = sellerService.sellerLogin(sellerAccount, sellerPassword);
				if (seller != null) {
					// 登录成功
					// 用户信息存储在session会话作用域中
					HttpSession session = request.getSession();
					session.setAttribute("seller", seller);

					// 获取复选框的值
					String rememberPassword = request.getParameter("rememberPassword");

					// 用户选择记住密码
					if (rememberPassword != null) {
						// 通过Servlet像cookie添加用户信息并发送给HTTP
						Cookie cookie = new Cookie(sellerAccount, sellerPassword);
						// 设置cookie有效时间
						cookie.setMaxAge(60 * 5);
						// 将cookie发送给HTTP
						response.addCookie(cookie);
					} else {
						// 用户选择不记住密码，通过Servlet删除Cookie（setMaxAge(0)），读取并存储新Cookie并发送给HTTP
						Cookie[] cookies = request.getCookies();
						Cookie cookie = null;
						for (int i = 0; i < cookies.length; i++) {
							cookie = cookies[i];
							if (cookie.getName().equals(sellerAccount)) {
								cookie.setMaxAge(0);
								response.addCookie(cookie);
							}
						}
					}// 重定向到首页
					response.sendRedirect("sellerIndex.jsp");
				} else {
					// 登录失败
					// 重定向到登录页面
					response.sendRedirect("sellerSignIn.jsp?loginErrorMessage=error");
				}
					
					
					
				}
		
	
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
